﻿using System;
using System.Web;
using System.Web.Security;
using Newtonsoft.Json;

namespace IrisMembership.Web.Authentication
{
    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        private readonly HttpContextBase _httpContext;

        public FormsAuthenticationService(HttpContextBase httpContext)
        {
            _httpContext = httpContext;
        }

        #region IFormsAuthenticationService Members

        public void SignIn(UserTicket userTicket, bool createPersistentCookie)
        {
            if (userTicket == null)
                throw new ArgumentNullException("userTicket");

            var cookie = new IrisCookie
            {
                UserId = userTicket.UserId,
                UserName = userTicket.UserName,
                Name = userTicket.Name
            };

            var userData = JsonConvert.SerializeObject(cookie);

            var ticket = new FormsAuthenticationTicket(2, cookie.UserName, DateTime.Now,
                                                       DateTime.Now.Add(FormsAuthentication.Timeout),
                                                       createPersistentCookie, userData);

            var encTicket = FormsAuthentication.Encrypt(ticket);

            var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
            {
                Expires = DateTime.Now.Add(FormsAuthentication.Timeout),
                HttpOnly = true,
            };

            _httpContext.Response.Cookies.Add(httpCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        #endregion
    }
}